package com.cmpe.av;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import com.cmpe.av.logic.ReportLogic;
import com.cmpe.av.model.ObstacleType;
//import com.oreilly.servlet.MultipartRequest;
import com.cmpe.av.utils.Utils;

/**
 * Servlet implementation class addReport
 */
@WebServlet("/addReport")
public class addReport extends HttpServlet {

	private List<ObstacleType> obstacles;
	private boolean isMultipart;

		private String audioPath = Utils.audioPath;
		private String videoPath = Utils.videoPath;
		private String imagePath = Utils.imagePath;
//	private String audioPath = "c:\\asd\\";
//	private String videoPath = "c:\\asd\\";
//	private String imagePath = "c:\\asd\\";

		private String tempPath = Utils.tempPath;
//	private String tempPath = "c:/asd/temp";


	private int maxFileSize = 50 * 1024 *1024;
	private int maxMemSize = 4 * 1024;
	private File file ;
	private static final long serialVersionUID = 1L;

	/**
	 * @see HttpServlet#HttpServlet()
	 */
	public addReport() {
		super();
		// TODO Auto-generated constructor stub
	}

	/**
	 * @see HttpServlet#doGet(HttpServletRequest request, HttpServletResponse
	 *      response)
	 */
	protected void doGet(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {

	}

	protected void doPost(HttpServletRequest request,
			HttpServletResponse response) throws ServletException, IOException {
		FileItem audioFileItem =null;
		FileItem imageFileItem = null;
		FileItem videoFileItem = null;	
		String reportName = "";
		double latitude = 0.0;
		double longitude = 0.0;
		int obstacleID = 0;
		String description = "";
		String statusName = "";
		String tags = "";
		String button ="";
		// Check that we have a file upload request
		isMultipart = ServletFileUpload.isMultipartContent(request);
		java.io.PrintWriter out = response.getWriter( );
		if( !isMultipart ){
			return;
		}
		DiskFileItemFactory factory = new DiskFileItemFactory();
		// maximum size that will be stored in memory
		factory.setSizeThreshold(maxMemSize);
		// Location to save data that is larger than maxMemSize.
		//	      factory.setRepository(new File("/home/project6/upload/temp"));
		//		factory.setRepository(new File(tempPath));
		factory.setRepository(new File(tempPath));

		// Create a new file upload handler
		ServletFileUpload upload = new ServletFileUpload(factory);
		// maximum file size to be uploaded.
		upload.setSizeMax( maxFileSize );
		int imageNum=0;
		int audioNum=0;
		int videoNum=0;
		int userIDfromAndroid=-2;
		String userAgent = request.getHeader("User-Agent");
		try{ 
			// Parse the request to get file items.
			List<FileItem> fileItems = upload.parseRequest(request);
			// Process the uploaded file items
			Iterator<FileItem> i = fileItems.iterator();

			while ( i.hasNext () ) 
			{
				FileItem fi = i.next();
				if ( !fi.isFormField ())	
				{
					if(userAgent.equals("android")){

						if(fi.getFieldName().contains("video")){
							videoFileItem = fi;
							videoNum++;
						}else if(fi.getFieldName().contains("image")){
							imageFileItem = fi;
							imageNum++;
						}else if(fi.getFieldName().contains("audio")){
							audioFileItem = fi;
							audioNum++;
						}
					}else{
						if( fi.getContentType().contains(fi.getFieldName()) ){
							// Get the uploaded file parameters
							String contentType = fi.getContentType();
							long sizeInBytes = fi.getSize();
							// Write the file
							if(contentType.contains("video")){
								videoFileItem = fi;
								videoNum++;
							}else if(contentType.contains("image")){
								imageFileItem = fi;
								imageNum++;
							}else if(contentType.contains("audio")){
								audioFileItem = fi;
								audioNum++;
							}

						}
					}
				}else{ 
					if (fi.getFieldName().equals("reportName")) 
						reportName = fi.getString();
					else if (fi.getFieldName().equals("locationFieldLat")){ 
						try{
							latitude = Double.parseDouble(fi.getString());
						}
						catch(NumberFormatException ignored){ 
						}
					}
					else if (fi.getFieldName().equals("locationFieldLong")){ 
						try{
							longitude = Double.parseDouble(fi.getString());	 
						}
						catch(NumberFormatException ignored){
						}
					}
					else if (fi.getFieldName().equals("obstacleType")) 
						try{
							obstacleID = Integer.parseInt(fi.getString());	 
						}
						catch(NumberFormatException ignored){
						}
					else if (fi.getFieldName().equals("userIDandroid")) 
						try{
							userIDfromAndroid = Integer.parseInt(fi.getString());	 
						}
						catch(NumberFormatException ignored){
						}
					else if (fi.getFieldName().equals("reportDescription")) 
						description = fi.getString();
					else if (fi.getFieldName().equals("status")) 
						statusName = fi.getString();
					else if (fi.getFieldName().equals("tags")) 
						tags = fi.getString();
					else if (fi.getFieldName().equals("button")) 
						button = fi.getString();    
				}
			}
		}catch(Exception ex) {
			ex.printStackTrace();
		}
		ReportLogic msAccess;
		HttpSession session = request.getSession();
		String strErrMsg = null;
		int userID = -1;
		int status = getStatus(statusName);
		int rate=0;

		boolean submitted = false;


		if (button.equals("Add Report")){
			try {
				userID = Integer.parseInt(session.getAttribute("userID").toString());
				if (userID != -1 ) {
					submitted = true;
				} 
				else {
					strErrMsg = "Cannot be submitted. Please try again.";
				}
			} 

			catch (Exception e) {
				strErrMsg = "Cannot be submitted. Please try again.";
				e.printStackTrace();
			}
			if(request.getHeader("User-Agent").equals("android")){
				submitted = true;
				userID = userIDfromAndroid;
			}
			if (submitted == true ) {
				try{
					msAccess = new ReportLogic();
					if(latitude==0 && longitude==0){
						request.setAttribute("invalid", true);
						request.getRequestDispatcher("/addReport.jsp").forward(
								request, response);
					}
					else{

						int report_id=msAccess.addReport(reportName, obstacleID, userID, latitude, longitude, status, description, rate, imageNum,videoNum,audioNum);
						String[] tag=splitTags(tags);
						msAccess.addTags(report_id,tag);
						if(videoFileItem!=null){
							videoFileItem.write(new File(videoPath,report_id+"_"+videoNum+"."+getFileExtension(videoFileItem)));
						}
						if(audioFileItem!=null){
							audioFileItem.write(new File(audioPath,report_id+"_"+audioNum +"."+getFileExtension(audioFileItem)));
						}
						if(imageFileItem!=null){

							imageFileItem.write(new File(imagePath,report_id+"_"+imageNum +"."+getFileExtension(imageFileItem)));
						}

						request.getRequestDispatcher("homeMember.jsp").forward(request, response);
						
					}
				}
				catch (Exception e) {
					strErrMsg = "Cannot be submitted. Please try again.";
					System.out.println(e);
					System.out.println("hata2");
				}
			}
			else {
				request.setAttribute("flag", true);
				session.setAttribute("errorMsg", strErrMsg);
				request.getRequestDispatcher("/WEB-INF/addReport.jsp").forward(request,
						response);
			}
		}
		/*else if(button.equals("Return Home Page")){
			request.getRequestDispatcher("/WEB-INF/homeMember.jsp").forward(request,
					response);
		}*/



	}
	public String getFileExtension(FileItem fi){
		String fileName = fi.getName();
		int dotposition= fileName.lastIndexOf(".");
		return fileName.substring(dotposition + 1, fileName.length()); 
	}
	public List<ObstacleType> getObstacles(){
		ReportLogic msAccess;
		obstacles= new ArrayList<ObstacleType>();
		try{
			msAccess = new ReportLogic();
			obstacles=msAccess.getObstacles();
		}
		catch(Exception e){
			e.printStackTrace();
		}
		return obstacles;
	}

	public String[] splitTags(String tag){
		String[] tags=tag.split(",");
		return tags;
	}

	public static int getStatus(String statusName){
		if(statusName==null)
			statusName="";
		int status=0; //for "Detected"
		if(statusName.equals("InProgress"))
			status=1;
		else if(statusName.equals("Fixed"))
			status=2;
		else if(statusName.equals("FriendlyLocation"))
			status=3;
		return status;
	}

}